/**
 * 
 */
package array;

/**
 * @author Michael
 *
 */
public class RotateArrayInPlace {

	public static int[] rotateKPlacesToRight(int[] a, int k) {
		assert (a != null);
		if (k >= 0)
			k = k % a.length;
		else
			k = -(-k % a.length) + a.length;
		
		reverseSubArray(a, 0, a.length-1);
		reverseSubArray(a, 0, k-1);
		reverseSubArray(a, k, a.length - 1);
		
		return a;
	}
	
	public static void reverseSubArray(int[] a, int from, int to) {
		assert (a != null);
		assert(from <= to && to < a.length);
		
		while (from < to) {
			swap(a, from , to);
			from++;
			to--;
		}
	}
	
	public static void swap(int[] a, int n, int m) {
		assert (a != null);
		assert (n < a.length && m < a.length);
		assert (n != m);
		int temp = a[n];
		a[n] = a[m];
		a[m] = temp;
	}
	
	/**
	 * 
	 */
	public RotateArrayInPlace() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int[] a = { 0, 1, 2, 3, 4, 5 };
		a = rotateKPlacesToRight(a, -4);
		for (int i = 0; i < a.length; i++)
			System.out.print(a[i] + " ");

	}

}
